package com.wujilee.wujileenetty.demos.web.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @author liwuji
 * @date 2024/8/5
 * @desc 写入数据过多 阻塞了怎么提高速度？
 **/
@Slf4j
public class WriteService {
    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            if (selector.select(1000) == 0) {
                continue;
            }
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                try {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isAcceptable()) {
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        SelectionKey register = socketChannel.register(selector, SelectionKey.OP_READ, null);
                        StringBuffer sb = new StringBuffer();
                        for (Long i = 0L; i < 3000000000L; i++) {
                            sb.append("a");
                        }
                        ByteBuffer encode = Charset.defaultCharset().encode(CharBuffer.wrap(sb));
                            int write = socketChannel.write(encode);
                            System.out.println(" 服务端发送了" + write + "字节的数据");
                            if(encode.hasRemaining()){
                                // 在原来的基础上onRead事件上 新增写事件
                                register.interestOps(selectionKey.interestOps()+ SelectionKey.OP_WRITE);
                                // 这里要测试下 附件即写又读
                                register.attach(encode);
                            }
                    }
                    if(selectionKey.isWritable()){
                        ByteBuffer attachment =(ByteBuffer) selectionKey.attachment();
                        if(!attachment.hasRemaining()){
                            selectionKey.attach(null);
                            // 去掉可写事件
                            selectionKey.interestOps(selectionKey.interestOps()-SelectionKey.OP_WRITE);
                        }
                    }
                } catch (Exception e) {
                    log.error("服务端处理消息异常", e);
                }
            }
        }
    }

}
